<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Wechat\Controller;

use Com\Wechat\ThinkWechat;//微信
use User\Api\UserApi as UserApi;
use Think\Crypt\Driver\Des;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class IndexController extends WechatController {
	

	//显示界面
    public function index(){
    	
    	//获取用户信息
    	$user = D('Member');
    	$userinfo = $user->getWechatInfo(WID);
    	
    	//获取用户的微信账号信息
    	$weixinLogic = D('Weixin','Logic');
    	$weixin = $weixinLogic->detail(WID);
		
    	$weixin = new ThinkWechat($userinfo['token']);
    	
    	$data = $weixin->request();
		
	
		
    	$openid = $data['FromUserName'];
    	define('OPENID',$openid);
    	session('openid',$openid);
		list($content, $type) = $this->reply($data);
		
		
		
		$weixin->response($content, $type);
    }
    
    /**
     * 消息回复
     * @param array $data
     * @return Ambigous <multitype:string , multitype:string unknown >
     */
    protected function reply($data){
    	$openid = $data['FromUserName'];
    	//define('OPENID', $openid);
    	//如果是文本信息
    	if('text' == $data['MsgType']){
    		$reply = $this->replyKeywords($data['Content']);
    	//如果是事件
    	} elseif('event' == $data['MsgType']){
    		if('subscribe' == $data['Event']){
    			$reply = $this->replyEvent($data['Event'],$data['EventKey']);
    		}else if('unsubscribe' == $data['Event']){
    			$reply = $this->replyEvent('subscribe');
    		}else if('CLICK' == $data['Event']){
    			$reply = $this->replyClick($data['EventKey']);
    		}else {
    			$reply = $this->replyKeywords();
    		}
    		
//     		$reply = array('欢迎您关注麦当苗儿公众助手！', 'text');
    	} else if('location' == $data['MsgType']){
    			$reply = $this->replyLocation($data['Location_X'],$data['Location_Y']);
    	}else if('image' == $data['MsgType']) {
			$reply = $this->replyPic();
    	}else {
			exit;
    		$reply = array("未知消息类型", 'text');
    	}
    	
    	//如果还是空的
    	if(empty($reply)){
    		$EventLogic = D('Event','Logic');
    		$reply = $EventLogic->defaultReply(WID);
    	}
    	
    	return $reply;
    }
    
    public function replyPic(){
		$openid = session('openid');
    	$arr[] = array(
    			'Title' => '举报投诉',
    			'ImgPath' => 'http://question.jucheng01.net/Public/Member/images/1.jpg',
    			'Url' => C('WEB_ABSOLUTE_URL').'/wechat.php?s=question/index/openid/'.$openid,
				'BriefDescription'	=> '',
    	);
    	$data[] =$arr;
    	$data[] = 'news';
    	return $data;
    	
    }
	
	/**
     * 获取点击事件
     */
    protected function replyClick($key){

		
		$keyword = explode('_', $key);
    	$keyword[1] = $keyword[1] > 0 ? $keyword[1] : 0;
	
    	if($keyword[0] == 'text'){
    	    $TextmsgLogic = D('Textmsg','Logic');
    	    $textmsg = $TextmsgLogic->detail($keyword[1]);
			$data = array();
    	    $data[] = $textmsg['text'];
		    $data[] = 'text';
    	    return $data;
    	    
    	}
    	if( in_array($keyword['0'], array('news','onenews'))){
			$map = array(
			    'id'=>$keyword['1'],
			);
		}else {
			
				
			$map = array(
					'relation'=>$keyword['0'],
					//'id'=>$keyword['1'],
			);
				
		}
		
		$newsmsgLogic = D('Newsmsg','Logic');
			
		$newsmsg = $newsmsgLogic->detail($map);
			
		if($newsmsg['msgtype'] == 'onenews'){
			$data[][] = $newsmsg['configs'];
		}else{
			$data[] = $newsmsg['configs'];
		}
		
		$data[] = 'news';
		return $data;
    	
    }
    
    /**
     * 回复关键词
     * @param string $text 消息内容
     */
    protected function replyKeywords($text){
    	//解析关键词
    	$keywordLogic = D('Keywords','Logic');
    	$data = $keywordLogic->detail($text,WID);
    	if(!empty($data[0])){
    	    return $data;
    	}
    	return $data;
    	
    	
    }
    
    /**
     * 回复事件
     */
    protected function replyEvent($event,$eventkey){
    	
    	
    	//若是推广二维码扫描 记录分销商
    	$key = explode('_', $eventkey) ;
    	if($key[1]!=null){
    		//查找上一级分销商
    		$mytraderLogic = D('DistributionMytrader','Logic');
    		$res=$mytraderLogic->where(array('openid'=>session('openid')))->find();
    		if($res==null){
    			$vipLogic = D('Vip','Logic');
    			$percentageLogic = D('DistributionPercentage','Logic');
    			$incomeLogic = D('DistributionIncome','Logic');
    			//$accountLogic = D('DistributionAccount','Logic');
    			$account = $vipLogic->where(array('sceneid'=>$key[1]))->field('id,openid')->find();
    			//关注给上一级分享加积分
    			$percent=$percentageLogic->find();
    			$adata=array(
    					'accid'		=> $account['id'],
    					'createtime'=>date(time()),
    					'integral'  =>floatval($percent['fpercent']),
    					'type'      =>'share',
    					'openid'    =>$account['openid'],
    			);
    			$incomeLogic->add($adata);
    			
    			
    			//查找上两级分销商
    			$pretader = $mytraderLogic->where(array('openid'=>$account['openid']))->field('accid')->find();
    			//存入被邀请人信息
    			$data = array(
    					'type'		=> 'ticket',
    					'openid' 	=> session('openid'),
    					'accid'		=> $account['id'],
    					'preaccid' 	=> $pretader['accid'],
    					'createtime'=>date(time()),
    			);
    			$mytraderLogic->add($data);
    			if($pretader){
    				$pdata=array(
    						'accid'		=> $pretader['accid'],
    						'createtime'=>date(time()),
    						'integral'  =>$percent['spercent'],
    						'type'      =>'share',
    						'openid'    =>$pretader['openid'],
    				);
    				$incomeLogic->add($pdata);
    			}
    		}
    		
    		
    		
    	}
    	
    	
    	
    	$EventLogic = D('Event','Logic');
    	 
    	return $EventLogic->detail($event,WID);
    }
    
    /**  
    * 返回门店信息 
    * @param unknowtype 
    * @return return_type 
    * @author 明 
    * @date 2014-9-23下午16:32:00
    * @version v2.0.0 
    */
    protected  function replyLocation($lat,$lng){
    	$uid = WID;
    	//查询门店信息
    	$storesLogic = D('stores','Logic');
    	$map = array(
    			'uid'	=>	$uid,
    	);
    	$lists = $storesLogic->where($map)->select();
    		foreach ($lists as $key => $value) {
    			
    			$phones = explode("\n", $value['phone']);
    			foreach ($phones as $pke => $pvalue){
    				$phones[$pke] = trim($pvalue);
    			}
    			$lists[$key]['phone'] = $phones;
    			$lists[$key]['Title'] = $value['storename'].'【'.$value['address'].'】';
    			if ($value['banner']!= null){
    				$lists[$key]['ImgPath'] = $value['banner'];
    			}else {
    				$lists[$key]['ImgPath'] = 'http://weixin.jucheng01.net/Public/Member/images/stores.jpg';
    			}
    			$lists[$key]['distance'] = $this->GetDistance($lat,$lng,$value['primarylat'],$value['primarylng']);
				$lists[$key]['Url'] = 'http://api.map.baidu.com/marker?location='.$value['primarylat'].','.$value['primarylng'].'&title='.$value['storename'].'&name='.$value['storename'].'&content=&output=html';
    		}
    		foreach ($lists as $key => $value){
    			$distance[$key] = $value['distance'];
    		}
    		array_multisort($distance,SORT_NUMERIC,SORT_ASC,$lists);
	    	$arr = array(
    			'Title' => '查看门店相信信息',
    			'ImgPath' => 'http://weixin.jucheng01.net/Public/Member/images/stores.jpg',
    			'Url' => apiurl('stores',WID),
	    	);
			$lists[] = $arr;
			$data[] =$lists;
			$data[] = 'news';
			return $data;
		  
    }
    
    /**  
    * 根据经纬度计算距离 
    * @param $lat经度$lng维度
    * @return return_type 
    * @author 明 
    * @date 2014-9-23下午3:29:01
    * @version v1.0.0 
    */
    public function GetDistance($lat1, $lng1, $lat2, $lng2)
    {
    	$EARTH_RADIUS = 6378.137;
    	$radLat1 = $this->rad($lat1);
    	$radLat2 = $this->rad($lat2);
    	$a = $radLat1 - $radLat2;
    	$b = $this->rad($lng1) - $this->rad($lng2);
    	$s = 2 * asin(sqrt(pow(sin($a/2),2) +
    			cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)));
    	$s = $s *$EARTH_RADIUS;
    	$s = round($s * 10000) / 10000;
    	return $s;
    }
    public function rad($d)
    {
    	return $d * 3.1415926535898 / 180.0;
    }
//     /**
//      * 访问api接口
//      */
//     public function api($uid,$module){
    	
//     }
    
	
    
   /**
    * 返回商家
    * @date: 2015-5-22
    * @author: 琴
    * @return:
    */
    public function replayData($moudle){
    	$newsmsgLogic = D('Newsmsg','Logic');
    	$keywordsLogic = D('Keywords','Logic');
    	$uid = WID;
    	//查询所有的预约信息
    	$map = array(
    			'uid'	=>	$uid,
    			'msgtype' => $moudle,
    	);
    	$info = $keywordsLogic->where($map)->find();
    	$msg = $newsmsgLogic->where(array('id'=>$info['msgid']))->find();
    	$msgconfig = serializeMysql($msg['configs'],1);
    	$info['Url'] = C('WEB_ABSOLUTE_URL').'/wechat.php?s='.$moudle.'/index/u/'.$uid;
    	$data =$info;
    	return $data;
    }
    
    
}